package com.xnyzc.lhy.mis.service.impl.cms.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.component.convert.DateToStringConverter;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.order.EOrderOperation;
import com.xnyzc.lhy.common.penum.pay.EFeeType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.mis.entity.gps.OaDVehicleGpsHistory;
import com.xnyzc.lhy.mis.entity.order.OaDOrder;
import com.xnyzc.lhy.mis.entity.order.OaOrderFeeRecord;
import com.xnyzc.lhy.mis.entity.order.OaServiceOrderOperationRecord;
import com.xnyzc.lhy.mis.entity.param.cms.order.CmsOadOrderPersonalParam;
import com.xnyzc.lhy.mis.entity.result.cms.order.CmsOrderChangePrice;
import com.xnyzc.lhy.mis.entity.result.cms.order.CmsOrderOperationRecordDetailRes;
import com.xnyzc.lhy.mis.entity.result.cms.order.CmsOrderTrajectoryPointResults;
import com.xnyzc.lhy.mis.entity.result.order.OrderLogMo;
import com.xnyzc.lhy.mis.entity.system.OaSysGlobalConfig;
import com.xnyzc.lhy.mis.feign.statistics.OrderTrajectoryService;
import com.xnyzc.lhy.mis.mapper.gps.OaDVehicleGpsHistoryMapper;
import com.xnyzc.lhy.mis.mapper.gps.OaSysTrajectoryMapper;
import com.xnyzc.lhy.mis.mapper.order.OaDOrderMapper;
import com.xnyzc.lhy.mis.mapper.order.OaOrderFeeRecordMapper;
import com.xnyzc.lhy.mis.mapper.order.OaServiceOrderOperationRecordMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysGlobalConfigMapper;
import com.xnyzc.lhy.mis.service.cms.order.CmsOrderOperationRecordService;
import com.xnyzc.lhy.order.entity.gps.OaSysTrajectory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.ArrayList;
import java.util.List;


/**
 * 订单详情中操作记录
 *
 * @Author wangshuo
 */
@Service
public class CmsOrderOperationRecordServiceImpl implements CmsOrderOperationRecordService {


    @Autowired
    private OaOrderFeeRecordMapper oaOrderFeeRecordMapper;

    @Autowired
    private OaServiceOrderOperationRecordMapper oaServiceOrderOperationRecordMapper;

    @Autowired
    private OaSysGlobalConfigMapper oaSysGlobalConfigMapper;

    @Autowired
    private OaDOrderMapper oaDOrderMapper;

    @Autowired
    private OrderTrajectoryService orderTrajectoryService;

    @Autowired
    private OaSysTrajectoryMapper oaSysTrajectoryMapper;

    @Autowired
    private OaDVehicleGpsHistoryMapper oaDVehicleGpsHistoryMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 订单详情中操作记录
     *
     * @param cmsOadOrderPersonalParam
     * @return
     */
    @Override
    public Rv getCmsOrderOperationRecord(CmsOadOrderPersonalParam cmsOadOrderPersonalParam) {
        if(CheckUtil.strIsEmpty(cmsOadOrderPersonalParam.getOrderNo())){
            throw PangException.create(EErrorCode.missingArg);
        }
        OaSysGlobalConfig config=oaSysGlobalConfigMapper.selectOne(null);

        List<CmsOrderOperationRecordDetailRes> resList=new ArrayList<>();
        List<CmsOrderChangePrice> changeList=new ArrayList<>();
        List<CmsOrderChangePrice> refundList=new ArrayList<>();

        QueryWrapper feeQueryWrapper = new QueryWrapper();
        feeQueryWrapper.eq(OaOrderFeeRecord.ORDER_NO ,cmsOadOrderPersonalParam.getOrderNo());
        List<OaOrderFeeRecord> feeList = oaOrderFeeRecordMapper.selectList(feeQueryWrapper);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaServiceOrderOperationRecord.ORDER_ID ,cmsOadOrderPersonalParam.getOrderNo());
        queryWrapper.orderByDesc(OaServiceOrderOperationRecord.CREATE_TIME);
        List<OaServiceOrderOperationRecord> recordList = oaServiceOrderOperationRecordMapper.selectList(queryWrapper);

        if(!recordList.isEmpty()){
            for(OaServiceOrderOperationRecord record:recordList){
                CmsOrderOperationRecordDetailRes result = new CmsOrderOperationRecordDetailRes();
                result.setOperationName(EOrderOperation.findById(record.getOperationType()).getValue());
                result.setBearer("");
                result.setOperation("");
                result.setWorkNo(record.getWorksheetId());
                result.setTime(new DateToStringConverter().convert(record.getCreateTime()));
                if(CheckUtil.strIsNotEmpty(record.getOperation())){
                    result.setOperation(record.getOperation());
                }
                if(CheckUtil.strIsNotEmpty(record.getBearer())){
                    result.setBearer(record.getBearer());
                }
                result.setOperationType(record.getOperationType());
                if(!feeList.isEmpty()){
                    for(OaOrderFeeRecord fee:feeList){
                        if(fee.getUpdateType()==0 && record.getOperationType().equals(EOrderOperation.change.getType())){
                            // 改价
                            CmsOrderChangePrice change=new CmsOrderChangePrice();
                            change.setName(EFeeType.findById(fee.getFeeType()).getValue());
                            change.setOldMoney(fee.getOriginlFee()+MessageConstant.MONEY_NAME);
                            if(fee.getOriginlFee().compareTo(fee.getDiffFee())==0){
                                change.setNewMoney(fee.getDiffFee()+MessageConstant.MONEY_NAME);
                            }else{
                                change.setNewMoney(config.getSetColor()+fee.getDiffFee()+MessageConstant.MONEY_NAME+"</span>");
                            }
                            changeList.add(change);
                        }
                        if(fee.getUpdateType()==1 && record.getOperationType().equals(EOrderOperation.refund.getType())){
                            // 退款
                            if(fee.getOriginlFee().compareTo(fee.getDiffFee())!=0){
                                CmsOrderChangePrice change=new CmsOrderChangePrice();
                                change.setName(EFeeType.findById(fee.getFeeType()).getValue()+MessageConstant.REFUND_NAME);
                                change.setNewMoney(config.getSetColor()+fee.getDiffFee()+MessageConstant.MONEY_NAME+"</span>");
                                refundList.add(change);
                            }
                        }
                    }
                }
                result.setChangePriceList(changeList);
                result.setRefundPriceList(refundList);
                resList.add(result);
            }
        }
        return Rv.wrap(resList);
    }

    /**
     * 订单轨迹打点
     *
     * @param param
     * @return
     */
    @Override
    public Rv getCmsOrderTrajectoryPoint(CmsOadOrderPersonalParam param) {
        if(CheckUtil.strIsEmpty(param.getOrderNo())){
            throw PangException.create(EErrorCode.missingArg);
        }
        QueryWrapper dOrderQueryWrapper = new QueryWrapper();
        dOrderQueryWrapper.eq(OaDOrder.ORDER_NO, param.getOrderNo());
        OaDOrder dOrder = oaDOrderMapper.selectOne(dOrderQueryWrapper);
        CmsOrderTrajectoryPointResults results=new CmsOrderTrajectoryPointResults();
        if(CheckUtil.objIsNotEmpty(dOrder)){
            // 司机去接乘客
            if(CheckUtil.objIsNotEmpty(dOrder.getPickPassengersFlat(),dOrder.getPickPassengersFlng())){
                results.setPickPassengers(dOrder.getPickPassengersFlng() + "," + dOrder.getPickPassengersFlat());
            }
            // 司机达到预约地点
            if(CheckUtil.objIsNotEmpty(dOrder.getArriveReservationFlat(),dOrder.getArriveReservationFlng())){
                results.setArriveReservation(dOrder.getArriveReservationFlng() + "," + dOrder.getArriveReservationFlat());
            }
            // 乘客已上车
            if(CheckUtil.objIsNotEmpty(dOrder.getActualFlat(),dOrder.getActualFlng())){
                results.setActualStart(dOrder.getActualFlng() + "," + dOrder.getActualFlat());
            }
            // 到达目的地
            if(CheckUtil.objIsNotEmpty(dOrder.getActualTlat(),dOrder.getActualTlng())){
                results.setActualEnd(dOrder.getActualTlng() + "," + dOrder.getActualTlat());
            }
            // 司机发送账单
            if(CheckUtil.objIsNotEmpty(dOrder.getInitiatePaymentFlat(),dOrder.getInitiatePaymentFlng())){
                results.setInitiatePayment(dOrder.getInitiatePaymentFlng() + "," + dOrder.getInitiatePaymentFlat());
            }
        }
        List<String> trajectoryResultsList = new ArrayList<>();
        List<String> historyResultsList = new ArrayList<>();

//        // 获取预估轨迹
//        Rv trajectoryRv=orderTrajectoryService.getPredictedTrajectory(param.getOrderNo());
//        if(CheckUtil.objIsNotEmpty(trajectoryRv)){
//            if(CheckUtil.objIsNotEmpty(trajectoryRv.getData())){
//                String dataStr = JSON.toJSONString(trajectoryRv.getData());
//                List<OaSysTrajectory>  trajectoryList = JSONObject.parseArray(dataStr, OaSysTrajectory.class);
//                if(!trajectoryList.isEmpty()){
//                    for(OaSysTrajectory trajectory:trajectoryList){
//                        trajectoryResultsList.add(trajectory.getLng() + "," + trajectory.getLat());
//                    }
//                }
//            }
//        }
//        // 获取行驶轨迹
//        Rv historyRv=orderTrajectoryService.getOrderTrajectory(param.getOrderNo());
//        if(CheckUtil.objIsNotEmpty(historyRv)){
//            if(CheckUtil.objIsNotEmpty(historyRv.getData())){
//                String dataStr = JSON.toJSONString(historyRv.getData());
//                List<OaDVehicleGpsHistory>  historyList = JSONObject.parseArray(dataStr, OaDVehicleGpsHistory.class);
//                if(!historyList.isEmpty()){
//                    for (OaDVehicleGpsHistory history:historyList) {
//                        historyResultsList.add(history.getLng() + "," + history.getLat());
//                    }
//                }
//            }
//        }
        // 行驶轨迹
        QueryWrapper historyQueryWrapper = new QueryWrapper();
        historyQueryWrapper.eq(OaDVehicleGpsHistory.ORDER_NO, param.getOrderNo());
        List<OaDVehicleGpsHistory> historyList = oaDVehicleGpsHistoryMapper.selectList(historyQueryWrapper);
        if(!historyList.isEmpty()){
            for (OaDVehicleGpsHistory history:historyList) {
                historyResultsList.add(history.getLng() + "," + history.getLat());
            }
        }
        // 预估轨迹
        QueryWrapper trajectoryQueryWrapper = new QueryWrapper();
        trajectoryQueryWrapper.eq(OaSysTrajectory.ORDER_NO, param.getOrderNo());
        List<OaSysTrajectory> trajectoryList = oaSysTrajectoryMapper.selectList(trajectoryQueryWrapper);
        if(!trajectoryList.isEmpty()){
            for(OaSysTrajectory trajectory:trajectoryList){
                trajectoryResultsList.add(trajectory.getLng() + "," + trajectory.getLat());
            }
        }
        results.setHistoryList(historyResultsList);
        results.setTrajectoryList(trajectoryResultsList);
        return Rv.wrap(results);
    }

    @Override
    public Rv getOrderOperationLog(String orderNo) {
        Query query = new Query();
        Sort sort = new Sort(Sort.Direction.ASC, "operateTime");
        query.addCriteria(new Criteria("orderNo").is(orderNo));
        List<OrderLogMo> orderLogMos = mongoTemplate.find(query.with(sort), OrderLogMo.class);
        return Rv.wrap(orderLogMos);
    }


}
